<template>
    <!-- 整体容器 -->
    <div class="pages">
        <el-container class="page-container">
            <!-- 搜索 -->
            <el-header class="page-header">
                <el-space :size="10">
                    <el-input v-model.trim="lookupData.spuName" placeholder="请输入商品名称" clearable />
                    <el-input v-model.trim="lookupData.id" placeholder="请输入团购ID" clearable />
                    <el-select v-model="lookupData.status" placeholder="请选择团购状态" clearable>
                        <el-option v-for="(item,index) in adStatusMap" :key="index" :label="item.name"
                            :value="item.value" />
                    </el-select>
                    <el-button type="primary" :icon="Search" @click="handlerLookupGroupPurchase">查找</el-button>
                    <el-button type="primary" :icon="Plus" @click="handlerAddGroupPurchase">添加</el-button>
                </el-space>
            </el-header>
            <el-main class="page-main">
                <!-- 表格 -->
                <div class="main-table">
                    <el-table :data="tableData" border style="width: 100%">
                        <el-table-column type="expand">
                            <template #default="props">
                                <div m="4">
                                    <!-- 描述详情列表 -->
                                    <el-descriptions :column="1" border>
                                        <el-descriptions-item label="类目ID" width="80px">
                                            {{props.row.categoryId }}
                                        </el-descriptions-item>
                                        <el-descriptions-item label="商品sku属性" width="80px" align="center">
                                            <!-- 嵌套表格 -->
                                            <el-table :data="props.row.groupShopSkuDTOList" border>
                                                <el-table-column label="SkuID" prop="skuId" align="center" />
                                                <el-table-column label="规格标题" prop="title" align="center" />
                                                <el-table-column label="团购价格(元)" prop="skuGroupShopPrice"
                                                    align="center" />
                                                <el-table-column label="库存" align="center">
                                                    <template #default="scope">
                                                        {{scope.row.stock}}(件)
                                                    </template>
                                                </el-table-column>
                                                <el-table-column label="原始价格(元)" prop="originalPrice" align="center" />
                                                <el-table-column label="售卖价格(元)" prop="price" align="center" />
                                                <el-table-column label="会员价格(元)" prop="vipPrice" align="center" />
                                                <el-table-column label="国际条码" prop="barCode" align="center" />
                                            </el-table>
                                        </el-descriptions-item>
                                    </el-descriptions>
                                </div>
                            </template>
                        </el-table-column>
                        <!-- 大表格数据 -->
                        <el-table-column label="团购ID" prop="id" align="center" />
                        <el-table-column label="商品ID" prop="spuId" align="center" />
                        <el-table-column label="商品名称" prop="title" align="center" width='400px'/>
                        <el-table-column label="商品主图" align="center">
                            <template #default="scope">
                                <el-popover placement="right" :width="300"
                                    :popper-style="'background-color:'+scope.row.color">
                                    <template #reference>
                                        <el-image style="height: 30px" :src="scope.row.img" fit="contain" />
                                    </template>
                                    <template #default>
                                        <div style="display: flex;align-items: center">
                                            <el-image :src="scope.row.img" fit="contain" />
                                        </div>
                                    </template>
                                </el-popover>
                            </template>
                        </el-table-column>
                        <el-table-column label="未满策略" align="center">
                            <template #default="scope">
                                <el-tag :type="scope.row.automaticRefund==0?'danger':'success'">
                                    {{scope.row.automaticRefund==0?'发货':'退款'}}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="活到状态" align="center">
                            <template #default="scope">
                                <el-tag :type="scope.row.status==0?'danger':'success'">
                                    {{scope.row.status==0?'冻结':'激活'}}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="开始时间" align="center">
                            <template #default="scope">
                                <span v-if="scope.row.gmtStart">
                                    {{new Date(scope.row.gmtStart).friendlyTime(3)}}
                                </span>
                                <span v-else>无</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="结束时间" align="center">
                            <template #default="scope">
                                <span v-if="scope.row.gmtEnd">
                                    {{new Date(scope.row.gmtEnd).friendlyTime(3)}}
                                </span>
                                <span v-else>无</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="当前人数" prop="buyerNum" align="center" />
                        <el-table-column label="目标人数" prop="minNum" align="center" />
                        <el-table-column label="操作" align="center" width="160px">
                            <template #default="scope">
                                <el-button type="primary" @click="handlerGroupPurchase(scope.row)">编辑</el-button>
                                <el-button type="danger" @click="handlerDeleteGroupPurchase(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <!-- 分页 -->
                <div class="page-pagination">
                    <Pagination v-bind="advertisPaging" @handle-pagination="emitEntProps" />
                </div>
                <!-- 抽屉弹出框 -->
                <el-drawer v-model="refDrawer" :show-close="false" direction="ltr" size="600px">
                    <template #header="{ close, titleId, titleClass }">
                        <h4 :id="titleId" :class="titleClass">{{refTitle}}团购商品</h4>
                        <el-button @click="close">取消</el-button>
                        <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
                    </template>
                    <h4 style="padding-left:20px;margin-top: 20px;">商品属性(spu)</h4>
                    <!-- 表单数据 -->
                    <el-form ref="ruleFormRef" :model="drawerRuleForm" status-icon :rules="rules" label-width="160px"
                        class="demo-ruleForm" label-position="left" style="padding: 30px 20px 40px 50px;">
                        <el-form-item label="团购商品" prop="spuId">
                            <el-cascader :options="cascaderCommodity" :props="commodityProps" @change="getTuanGouID"
                                v-model="drawerRuleForm.spuId " />
                        </el-form-item>
                        <el-form-item label="团购时间" prop="gmtTime">
                            <el-col :span="10">
                                <el-date-picker v-model="drawerRuleForm.gmtStart" value-format="x" type="datetime"
                                    placeholder="选择开始日期" style="width: 100%" />
                            </el-col>
                            <el-col :span="4" style="text-align: center;">
                                <span>至</span>
                            </el-col>
                            <el-col :span="10">
                                <el-date-picker v-model="drawerRuleForm.gmtEnd" value-format="x" type="datetime"
                                    placeholder="选择结束日期" style="width: 100%" />
                            </el-col>
                        </el-form-item>
                        <el-form-item label="团购基础人数" prop="minNum">
                            <el-input-number v-model="drawerRuleForm.minNum" :min="1" :max="999"
                                controls-position="right" />
                        </el-form-item>
                        <el-form-item label="活动结束时人数没有达到基础人数采取:">
                            <el-radio-group v-model="drawerRuleForm.automaticRefund" style="width:100%">
                                <el-radio-button label=0>不退款,我要发货</el-radio-button>
                                <el-radio-button label=1>自动退款,我不发货</el-radio-button>
                            </el-radio-group>
                        </el-form-item>
                    </el-form>
                    <!-- 表格数据 -->
                    <div class="drawer-table-title">
                        <h4 style="padding-left:20px">商品类型(sku)</h4>

                        <el-popover v-model:visible="refVisible" placement="right" :width="300">
                            <el-form-item label="团购价格">
                                <el-input-number v-model="drawergDialogForm.skuGroupShopPrice" :min="1" :max="99999"
                                    controls-position="right" style='margin-right: 10px;' />元
                            </el-form-item>
                            <div style="text-align: center; margin: 0">
                                <el-button @click="refVisible = false">取消</el-button>
                                <el-button type="primary" @click="healderVisible">确定</el-button>
                            </div>
                            <template #reference>
                                <el-button style="margin-right:20px" type="primary" plain>批量定价</el-button>
                            </template>
                        </el-popover>
                    </div>
                    <div style="margin:20px;border-top:1px solid #EBEEF5;padding-top: 16px;">
                        <el-table :data="drawerTableData" style="width: 100%">
                            <el-table-column prop="spuId" label="SkuId" />
                            <el-table-column prop="barCode" label="Sku条形码" />
                            <el-table-column prop="title" label="类型名" />
                            <el-table-column prop="stock" label="库存" />
                            <el-table-column prop="originalPrice" label="现价/元" />
                            <el-table-column prop="skuGroupShopPrice" label="团购价格/元" />
                            <el-table-column prop="操作" label="操作">
                                <template #default="scope">
                                    <el-button type="primary" @click="updateDrawerTable(scope.row,scope.$index)">更新</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </el-drawer>
                <!-- 抽屉弹出框表格更新对话框 -->
                <el-dialog v-model="dialogFormVisible" title="更新团购价格">
                    <el-form :model="drawergDialogForm"  label-width="120px" label-position="left" style="padding:0px 20px">
                        <el-form-item label="团购价格">
                            <el-input-number v-model="drawergDialogForm.minskuGroupShopPrice" :min="1" :max="99999"
                                    controls-position="right" style='margin-right: 10px;' />元
                        </el-form-item>
                        <el-form-item label="现价">
                            {{drawergDialogForm.originalPrice}}
                        </el-form-item>
                        <el-form-item label="sku类型名">
                            {{drawergDialogForm.specification}}
                        </el-form-item>
                    </el-form>
                    <template #footer>
                        <span class="dialog-footer">
                            <el-button @click="dialogFormVisible = false">取消</el-button>
                            <el-button type="primary" @click="healderWhenUpdate">确定</el-button>
                        </span>
                    </template>
                </el-dialog>
            </el-main>
        </el-container>
    </div>
</template>

<script lang="ts" setup>
import { ClassPagination, ClassDrawerRuleForm } from '#/index';
import { reactive, ref } from 'vue';
import { Search, Plus } from '@element-plus/icons-vue';
import { post } from "@/utils/index";
import { ElMessage,ElMessageBox } from 'element-plus';
import type { FormInstance } from 'element-plus'

const ruleFormRef = ref<FormInstance>()
// 获取分页的数据
const advertisPaging = reactive(new ClassPagination())
// 获取抽屉表格的数据
const drawerTableData:TypeGroupPurchaseChild[] = reactive([])
// 搜索栏数据类型
const lookupData = reactive({
    id: '',
    spuName: '',
    status: ''
})
// 团购状态
const adStatusMap = reactive([
    { value: 0, name: '冻结' },
    { value: 1, name: '激活' },
])
const refTitle = ref("创建")
// 表格渲染数据类型
const tableData: TypeGroupPurchase[] = reactive([])
// 抽屉显示隐藏
const refDrawer = ref(false)
// 抽屉弹出框表格更新对话框显示隐藏
const dialogFormVisible = ref(false)
// 抽屉弹出框表格批量定价弹出框显示隐藏
const refVisible = ref(false)
// 抽屉表单数据类型
const drawerRuleForm = reactive(new ClassDrawerRuleForm())
// 获取商品树
const cascaderCommodity: Array<object> = reactive([])
// 下拉选择树，子级配置
const commodityProps = reactive({
    emitPath: false,//返回数字类型数据，true返回数组类型数据
    children: 'children',
    value: 'id',
    label: 'label',
})
const drawergDialogForm = reactive({
    index:0,    // 下标
    skuGroupShopPrice:0,    //团购价格
    originalPrice:0,    //现价
    specification:'',   //sku类型名
    minskuGroupShopPrice:0  //团购价格
})
// 存储抽屉表单数据类型空值
const drawerRuleFormNull = reactive(new ClassDrawerRuleForm())

function validategmtTime (rule: Object, value: string, callback: Function) {
    if(drawerRuleForm.gmtEnd == '' && drawerRuleForm.gmtStart == ''){
        callback(new Error('团购时间不能为空'))
    } else if (drawerRuleForm.gmtEnd < drawerRuleForm.gmtStart) {
        callback(new Error('结束时间不能小于开始时间'))
    } else{
        callback()
    }
}
const rules = reactive({
    spuId: [{ required: true, message: '请选择团购商品', trigger: 'blur' }],
    gmtTime: [{ validator: validategmtTime, trigger: 'change' },],
})
// 抽屉弹出框的确定按钮函数
const submitForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            //判断所有sku商品是否存在团购价格
            let bool=drawerTableData.every(item=>item.skuGroupShopPrice)
                if(!bool){
                    ElMessage.error('团购价格不能为空')
                return 
                } 
            let data = {
                _gp:'admin.groupshop',
                _mt:refTitle.value == '创建'?'create':'edit',
                ...drawerRuleForm
            }
            // 转成字符串
            data.groupShopSkuList=JSON.stringify(drawerTableData)
            post(data).then((res) => {
                if(200 === res.errno){
                    getInitGroupPurchase()
                    refDrawer.value = false
                    ElMessage.success(refTitle.value == '创建'?'添加成功':'修改成功')
                }else{
                    ElMessage.error(res.errmsg)
                }
            })
        } else {
            return false
        }
    })
}
// 获取初始表格数据
function getInitGroupPurchase() {
    let data = {
        _gp: 'admin.groupshop',
        _mt: 'list',
        id: lookupData.id,
        spuName: lookupData.spuName,
        status: lookupData.status,
        page: advertisPaging.page,
        limit: advertisPaging.limit,
    }
    post(data).then((res) => {
        if (200 === res.errno) {
            let { items, total } = res.data
            tableData.length = 0
            tableData.push(...items)
            advertisPaging.total = total
        } else {
            tableData.length = 0
            ElMessage.warning(res.errmsg)
        }
    })
}
// 获取团购ID并请求表格数据
function getTuanGouID(e: number) {
    drawerTableData.length = 0
    getdrawerTableData(e)
}
// 获取抽屉表格的数据
function getdrawerTableData(e:number) {
    let data = {
        _gp: 'admin.product',
        _mt: 'detail',
        spuId: e
    }
    post(data).then((res) => {
        console.log(res);
        if (200 === res.errno) {
            // 将skuId 转为id
            res.data.skuList.forEach((item: { skuId: number; id: number }) => {
                item.skuId = item.id;
            });
            // 清零
            drawerTableData.length = 0
            // 进行赋值
            drawerTableData.push(...res.data.skuList)
        } else {
            ElMessage.error(res.errmsg)
        }
    })
}
/**
* 商品树形数据
*/
function getCommodity() {
    let data = {
        _gp: 'admin.product',
        _mt: 'getSpuBigTree'
    }
    post(data).then((res) => {
        if (200 === res.errno) {
            cascaderCommodity.length = 0
            cascaderCommodity.push(...res.data)
        }
    })
}
// 如果已经请求了那么就不用重复请求
if (cascaderCommodity.length <= 0) {
    getCommodity()
}
// 批量定价确定按钮
function healderVisible() {
    if(drawergDialogForm.skuGroupShopPrice > drawerTableData[drawergDialogForm.index].originalPrice){
        ElMessage.warning("团购价格不能大于原价")
        return
    }
    refVisible.value = false
    // 进行赋值
    drawerTableData.forEach(item=>{
        item.skuGroupShopPrice = drawergDialogForm.skuGroupShopPrice
    })
    // 赋值完成赋值为1
    drawergDialogForm.skuGroupShopPrice = 1
}
// 抽屉表格更新按钮
function healderWhenUpdate() {
    if(drawergDialogForm.minskuGroupShopPrice > drawerTableData[drawergDialogForm.index].originalPrice){
        ElMessage.warning("团购价格不能大于原价")
        return
    }
    // 更改单个团购价格
    Object.assign(drawerTableData[drawergDialogForm.index],{skuGroupShopPrice:drawergDialogForm.minskuGroupShopPrice})
    // 赋值完成赋值为1
    drawergDialogForm.minskuGroupShopPrice = 1
    dialogFormVisible.value = false
}
// 抽屉弹出框表格更新按钮函数
function updateDrawerTable(row:TypeGroupPurchaseChild,index:number) {
    dialogFormVisible.value = true
    // 进行赋值操作
    Object.assign(drawergDialogForm,row,{index})
}
// 查找团购订单
function handlerLookupGroupPurchase() {
    advertisPaging.page = 1
    getInitGroupPurchase()
}
// 添加团购订单
function handlerAddGroupPurchase() {
    // 赋值为空
    Object.assign(drawerRuleForm,drawerRuleFormNull)
    drawerTableData.length = 0
    refTitle.value = '创建'
    refDrawer.value = true
}
// 编辑团购订单
function handlerGroupPurchase(row: TypeGroupPurchase) {
    refTitle.value = '修改'
    refDrawer.value = true
    drawerTableData.length = 0
    drawerTableData.push(...row.groupShopSkuDTOList)
    // 使用forEach循环遍历key是否相同,如果相同则进行赋值
    Object.keys(drawerRuleForm).forEach(key=>{
        (drawerRuleForm as any)[key]=(row as any)[key]
    })
    // 调用一次请求,刷新数据
    getInitGroupPurchase()
}
// 删除团购订单
function handlerDeleteGroupPurchase(row: TypeGroupPurchase) {
    ElMessageBox.confirm(
        '确认是否删除?',
        '提示',
        { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning', }
    ).then(() => {
        post({
            _gp: 'admin.groupshop',
            _mt: 'delete',
            id: row.id,
        }).then(res => {
            if (200 === res.errno) {
                getInitGroupPurchase()
                ElMessage.success("删除成功")
            } else {
                ElMessage.error(res.errmsg)
            }
        })
    }).catch(() => {
        ElMessage.warning("已取消删除")
    })
}
/**
 * 分页组件传递过来的数据
 * @param val
 * page:页数
 * limit:条数
 */
function emitEntProps(val: { page: number, limit: number }) {
    let paging = advertisPaging
    paging.page = val.page
    paging.limit = val.limit
    getInitGroupPurchase()
}
// 初始请求
getInitGroupPurchase()
</script>

<style lang="less" scoped>
/deep/.el-drawer__body {
    padding: 0px;
}

// 抽屉弹出框表格标题样式
.drawer-table-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-top: 30px;
    border-top: 1px solid #e5ebf8;
    box-shadow: 0px -6px 20px -14px #666;

    .popover-dis {
        display: flex;
        align-items: center;
        justify-content: center;
    }
}
/deep/.el-drawer__header {
    margin-bottom: 0px;
    border-bottom-width: 32px;
    padding-bottom: 20px;
    border-bottom: 1px solid #e5ebf8;
}
</style>